/*
 * Copyright 2014 BOUVIER-VOLAILLE Julien
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include "service_loader.h"

#include <sstream>
#include <files.h>
#include <dlfcn.h>

namespace webcjson {

	service_loader& service_loader::getInstance(){
		 static service_loader instance;
		 return instance;
	}

	void service_loader::loadServices(){

		std::string iDeployedDir = http_properties::getInstance().get("deployed");
		std::vector<std::string> aLibList;
		files::listFilesFromDirectory(iDeployedDir, aLibList);

		for (int i=0; i<aLibList.size(); i++) {
		
			std::string aPathToLib = iDeployedDir+"/"+aLibList[i]; 

		     if (!files::isDirectory(aPathToLib)) {

				std::cout << "Trying to load service " << aLibList[i] << "..." << std::endl;

				void* handle = dlopen(aPathToLib.c_str(), RTLD_NOW);

				if (!handle) {
				     fprintf(stderr, "%s\n", dlerror());
				     return;
				}

				dlerror();
			}

		}
		
		std::cout << "Exiting from load service" << std::endl;

	}

	void service_loader::load(const std::string& iURI, service* iService){
		
		for (int i=0; i<_engines.size(); i++) {	
		 	_engines[i]->getServiceRecorder().record(iURI, iService);	
		}

	}	
	

}
